package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 144. 二叉树的前序遍历
 * 递归调用法
 *
 * @author fy
 * @date 2022/4/12 19:10
 */
public class Solution144 {

    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        preOrderTree(root, res);
        return res;
    }

    private void preOrderTree(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        }
        list.add(node.val);
        if (node.left != null) {
            preOrderTree(node.left, list);
        }
        if (node.right != null) {
            preOrderTree(node.right, list);
        }
    }

    /**
     * 简化版本, 可以不用判断 node 的左右节点是否为null, 只是调用的次数增多了而已
     *
     * @param node
     * @param list
     */
    private void preOrder(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        }
        list.add(node.val);
        preOrderTree(node.left, list);
        preOrderTree(node.right, list);
    }

    public static void main(String[] args) {
        Integer[] nums = new Integer[]{1, null, 2, 3};
        TreeNode root = BinaryTreeUtil.createTree(nums);
        BinaryTreeUtil.printTree(root);
        List<Integer> res = new Solution144().preorderTraversal(root);
        System.out.println(res);
    }
}
